package com.cory.utils.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

/**
 * Cookie 工具类
 * @author xiongcong
 * @date 2019-05-17
 */
public final class CookieUtils {

    /**
     * 得到Cookie的值
     */
    public static String getValue(HttpServletRequest request, String name) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || name == null) {
            return null;
        }
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(name)) {
                return cookieList[i].getValue();
            }
        }
        return null;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */
    public static void setCookie(HttpServletResponse response, String name,
            String value) {
        setCookie(response, name, value, -1);
    }

    /**
     * 设置Cookie的值 在指定时间内生效
     */
    public static void setCookie(HttpServletResponse response, String name,
            String value, int maxAge) {
        setCookie(response, name, value, maxAge, null, null);
    }

    /**
     * 删除Cookie
     */
    public static void removeCookie(HttpServletResponse response,
            String name) {
        setCookie(response, name, "", 0, null, null);
    }

    /**
     * 设置Cookie的值，并使其在指定时间内生效
     * 
     * @param maxAge cookie生效的最大秒数
     */
    public static final void setCookie(HttpServletResponse response,
            String name, String value, int maxAge, String domain, String path) {
        try {
            Cookie cookie = new Cookie(name, value);
            if (maxAge >= 0)
                cookie.setMaxAge(maxAge);
            if (StringUtils.isNotBlank(domain)) {
                cookie.setDomain(domain);
            }
            cookie.setPath(StringUtils.defaultIfBlank(path, "/"));
            response.addCookie(cookie);
        } catch (Exception e) {
             e.printStackTrace();
        }
    }

}